//
//  UIImageKLExtensions.m
//  TrainerApp
//
//  Created by Jesse Curry on 12/1/09.
//  Copyright 2009 Circonda, Inc.. All rights reserved.
//

#import "UIImageKLExtensions.h"

@implementation UIImage ( KLExtensions )
#pragma mark -
#pragma mark Class Methods
#pragma mark -
+ (UIImage*)imageWithColor: (UIColor*)color
{	
    CGRect rect = CGRectMake( 0.0f, 0.0f, 1.0f, 1.0f );
    UIGraphicsBeginImageContext( rect.size );
    CGContextRef context = UIGraphicsGetCurrentContext();
	
    CGContextSetFillColorWithColor( context, color.CGColor );
    CGContextFillRect( context, rect );
	
    UIImage* theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
	
    return theImage;
}

#pragma mark -
#pragma mark Instance Methods
- (UIImage*)thumbnailWithMaximumSize: (CGSize)maxSize
{
    CGSize size = [self size];
	CGFloat wRatio = 0;
	CGFloat hRatio = 0;
	CGFloat ratio = 0;
    
	wRatio = maxSize.width / size.width;
	hRatio = maxSize.height / size.height;
	ratio = MIN( wRatio, hRatio );
	
	CGRect rect = CGRectMake( 0.0, 
							 0.0, 
							 ratio * size.width, 
							 ratio * size.height );
    
    UIGraphicsBeginImageContext( rect.size );
    [self drawInRect: rect];
    UIImage* thumbnail = UIGraphicsGetImageFromCurrentImageContext();
	
	UIGraphicsEndImageContext();
	
	return thumbnail;
}

- (UIImage*)imageWithTint: (UIColor*)theColor 
{
    UIGraphicsBeginImageContext( self.size );
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake( 0, 0, self.size.width, self.size.height );
    
    CGContextScaleCTM( ctx, 1, -1 );
    CGContextTranslateCTM( ctx, 0, -area.size.height );
    
    CGContextSaveGState( ctx );
    CGContextClipToMask( ctx, area, self.CGImage );
    
    [theColor set];
    CGContextFillRect( ctx, area );
	
    CGContextRestoreGState( ctx );
    
    CGContextSetBlendMode( ctx, kCGBlendModeMultiply );
    
    CGContextDrawImage( ctx, area, self.CGImage );
	
    UIImage* tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return tintedImage;
}
@end
